package com.fay.basic.base.copy.reflection;

import java.lang.reflect.Array;
import java.util.Arrays;

/**
 * @Title:
 * @Description:
 * @Author Fay Wang
 * @Date 2022/5/13 17:00
 * @Version 1.0
 */
public class ArrayCopy {
    public static void main(String[] args) {
        int[] nums = {1, 2, 3};
        nums = (int[]) copyArrayResize(nums, 10);
        System.out.println(Arrays.toString(nums));

        String[] strArr = {"a", "b", "c"};
        strArr = (String[]) copyArrayResize(strArr, 12);
        System.out.println(Arrays.toString(strArr));
    }

    private static Object copyArrayResize(Object a, int newLength) {
        // 获取Class 对象
        Class<?> aClass = a.getClass();
        // 如果不是数组对象，就返回Null
        if (!aClass.isArray()) {
            return null;
        }
        // 获取数组的组件对象  类型：如String、int、Object等
        Class<?> componentType = aClass.getComponentType();
        // 获取原长度
        int oldLength = Array.getLength(a);
        // 用componentType和新长度，采用Array的静态工厂方法生成新对象，
        // 统一用Object，因为不知道来的是啥
        Object newArray = Array.newInstance(componentType, newLength);

        // 复制数组
        System.arraycopy(a, 0, newArray, 0, Math.min(newLength, oldLength));
        return newArray;
    }
}
